<!DOCTYPE html>
<html>
<head>
	<title>test_file_upload</title>
	<script type="text/javascript" src="../js/util.js"></script>
	<script type="text/javascript" src="../js/jquery.min.js"></script>
	<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
	<script type="text/javascript">
		function isExpectedFile(file) {
			return file.name == 'upload_this.png' &&
					file.size == 5417 && file.type == 'image/png';
		}
		function onNormalFileUploadChange(event) {
			var file = event.currentTarget.files[0];
			if (isExpectedFile(file)) {
				setResult("Success!");
			}
		}
		function enableDropEvent(onElement) {
			// If we don't 'preventDefault' on the events 'dragover' and
			// 'dragenter', the 'drop' event never reaches us. This function
			// ensures that the 'drop' event does get passed through. For a
			// reference, see http://www.quirksmode.org/blog/archives/2009/09/
			// the_html5_drag.html
			var preventDefault = function(event) {
				event.preventDefault();
			};
			onElement.on('dragover', preventDefault);
			onElement.on('dragenter', preventDefault);
		}
		/**
		 * The HTML5 spec at http://www.w3.org/html/wg/drafts/html/master/
		 * editing.html#current-drag-operation says that a drag consists of one
		 * dragenter event followed by a dragover event every 350+-200ms.
		 * The code below tests that the dragover event really is broadcast
		 * continuously by only considering dragover events 1000ms after the
		 * first dragenter event.
		 */
		var dragenterTime;
		$(document).on('dragenter', function(event) {
			dragenterTime = new Date().getTime();
			$("#dropFileUploadLabel").html('Now hold for 1 second...');
		});
		$(document).on('dragover', function(event) {
			var currTime = new Date().getTime();
			if (dragenterTime != undefined && currTime - dragenterTime > 1000) {
				var dropFileUpload = $('#dropFileUpload');
				dropFileUpload.addClass('active');
				enableDropEvent(dropFileUpload);
				dropFileUpload.on('drop', function(event) {
					event.preventDefault();
					var file = event.originalEvent.dataTransfer.files[0];
					if (isExpectedFile(file)) {
						setResult('Success!');
					}
				});
			}
		});
	</script>
	<style type="text/css">
		#dropFileUpload {
			border: 1px solid #aaaaaa;
			padding: 3px 10px;
			display: inline;
			visibility: hidden;
		}
		#dropFileUpload.active {
			visibility: visible;
		}
	</style>
</head>
<body>
	<label for="normalFileUpload">Normal file upload:</label>
	<input type="file" id="normalFileUpload"
		   onchange="onNormalFileUploadChange(event)"/>
	<br/>
	<label for="dropFileUpload" id="dropFileUploadLabel">
		Drag a file over this browser window!
	</label>
	<div id="dropFileUpload">Drop the file here!</div>
	<p id="result"></p>
</body>
</html>